package com.everbest.common.mdc;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.slf4j.MDC;

/**
 * @Author: obank_yk
 * @Date: 2019/8/1 14:14
 * @DESC: MDC过滤器配置,主要作用是用于日志报错跟踪
 */
public class MdcFilter implements Filter {

    public static String MDC_ID = "requestId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String mdcID = filterConfig.getInitParameter("MDC_ID");
        if (mdcID != null) {
            this.MDC_ID = mdcID;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        try {
            UUID logID = UUID.randomUUID();
            MDC.put(this.MDC_ID, logID.toString().replaceAll("-", ""));
            chain.doFilter(request, response);
        } finally {
            MDC.remove(this.MDC_ID);
        }
    }

    @Override
    public void destroy() {

    }
}
